import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/auth'
import store from '@/store'
import NProgress from 'nprogress' // 引入进度条
import 'nprogress/nprogress.css' // 引入进度条样式

// 使用懒加载导入组件
const Login = () => import('../views/Login.vue')
const Layout = () => import('../views/Layout.vue')
const Dashboard = () => import('../views/Dashboard.vue')
const NotFound = () => import('../views/404.vue')
const Redirect = () => import('../views/redirect/index.vue')
const UserIndex = () => import('../views/user/index.vue')
const UserProfile = () => import('../views/user/profile.vue')
const RoleIndex = () => import('../views/role/index.vue')
const MenuIndex = () => import('../views/menu/index.vue')
const DemoIndex = () => import('../views/demo/index.vue')
const Settings = () => import('../views/settings/index.vue')


// 修改NProgress配置
NProgress.configure({ showSpinner: false }) // 禁用加载微调器

Vue.use(VueRouter)

// 公共路由，所有用户都可以访问
export const constantRoutes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/redirect',
    component: Layout,
    hidden: true,
    children: [
      {
        path: '/redirect/:path(.*)',
        component: Redirect
      }
    ]
  },
  {
    path: '/404',
    component: NotFound,
    meta: { title: '404', requiresAuth: false },
    hidden: true
  },
]

// 需要根据权限动态加载的路由
export const asyncRoutes = [
  {
    path: '/',
    name: 'Layout',
    redirect: '/dashboard',
    component: Layout,
    meta: { title: '首页', requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: { title: '控制台', icon: 'el-icon-s-home', affix: true }
      }
    ]
  },
  {
    path: '/profile',
    component: Layout,
    hidden: true,
    children: [
      {
        path: '',
        name: 'Profile',
        component: UserProfile,
        meta: { title: '个人中心', icon: 'el-icon-user' }
      }
    ]
  },
  {
    path: '/settings',
    component: Layout,
    hidden: true,
    children: [
      {
        path: '',
        name: 'Settings',
        component: Settings,
        meta: { title: '系统设置', icon: 'el-icon-setting' }
      }
    ]
  },
  {
    path: '/system',
    component: Layout,
    redirect: '/system/user',
    name: 'System',
    meta: { title: '系统管理', icon: 'el-icon-s-tools', roles: ['admin', 'manager'] },
    children: [
      {
        path: 'user',
        name: 'User',
        component: UserIndex,
        meta: { title: '用户管理', icon: 'el-icon-user', roles: ['admin', 'manager'] }
      },
      {
        path: 'role',
        name: 'Role',
        component: RoleIndex,
        meta: { title: '角色管理', icon: 'el-icon-user-solid', roles: ['admin'] }
      },
      {
        path: 'menu',
        name: 'Menu',
        component: MenuIndex,
        meta: { title: '菜单管理', icon: 'el-icon-menu', roles: ['admin'] }
      },
      
    ]
  },
  {
    path: '/demo',
    component: Layout,
    children: [
      {
        path: '',
        name: 'Demo',
        component: DemoIndex,
        meta: { title: '组件演示', icon: 'el-icon-s-tools' }
      }
    ]
  },
  // 404页面必须放在最后
  { path: '*', redirect: '/404', hidden: true }
]

const createRouter = () => new VueRouter({
  mode: 'history',
  base: '/',
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})

const router = createRouter()

// 重置路由
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher
}

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  // 开启进度条
  NProgress.start()
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 后台管理系统` : '后台管理系统'
  
  // 获取token
  const hasToken = getToken()
  
  if (hasToken) {
    if (to.path === '/login') {
      // 已登录且要跳转的页面是登录页，重定向到首页
      next({ path: '/' })
      NProgress.done()
    } else {
      // 检查是否已加载动态路由
      const hasRoutes = store.getters.addRoutes && store.getters.addRoutes.length > 0
      
      // 检查是否已有用户角色
      const hasRoles = store.getters['user/roles'] && store.getters['user/roles'].length > 0
      
      if (hasRoutes) {
        // 已加载路由，检查目标路径是否存在
        // 根据路由配置，如果路径不存在会被redirect到404
        next()
      } else {
        try {
          // 确保有用户角色
          let roles = []
          if (!hasRoles) {
            // 获取用户信息
            const userData = await store.dispatch('user/getInfo')
            roles = userData.roles || ['admin']
          } else {
            // 使用已有角色
            roles = store.getters['user/roles']
          }
          
          // 生成可访问路由
          const accessRoutes = await store.dispatch('permission/generateRoutes', {
            roles,
            routes: asyncRoutes,
            constantRoutes
          })
          
          // 动态添加可访问路由
          router.addRoutes(accessRoutes)
          
          // 使用replace模式访问目标页面，避免导航重复
          next({ ...to, replace: true })
        } catch (error) {
          // 路由生成错误，重置令牌并重定向到登录页
          await store.dispatch('user/resetToken')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    // 未登录
    if (to.meta.requiresAuth === false) {
      // 不需要登录的页面，直接放行
      next()
    } else {
      // 需要登录的页面，重定向到登录页
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

// 全局后置钩子
router.afterEach(() => {
  // 关闭进度条
  NProgress.done()
})

export default router
